package com.iisageek.client.widgets.xml;

public class Element extends Node {
    private Node [] children;
    private String name;
    private String [] attributes;
    private String [] values;

    //creation API
    public Element(String name) {
	attributes=new String[0];
	values=new String[0];
	children=new Node[0];
	this.name=name;
    }

    public void addChild(Node child) {
	Node [] newChildren = new Node[children.length+1];
	for(int i=0;i<children.length;i++)
	    newChildren[i]=children[i];
	newChildren[children.length]=child;
	children=newChildren;
    }

    public void addAttribute(String key, String value) {
        String [] newKeys = new String[attributes.length+1];
	String [] newValues = new String[values.length+1];
	for(int i=0;i<attributes.length;i++) {
	    newKeys[i]=attributes[i];
	    newValues[i]=values[i];
	}
	newKeys[attributes.length]=key;
	newValues[attributes.length]=value;
	attributes=newKeys;
	values=newValues;
    }

    public Node [] getChildren() {
	return children;
    }

    // Node API implementation
    public boolean isElement() {
	return true;
    }

    public String getName() {
	return name;
    }
    
    public String getAttribute(String name) {
	for(int i=0;i<attributes.length;i++)
	    if(attributes[i].equals(name))
		return values[i];
	return null;
    }

    public String [] getAttributes() {
	return attributes;
    }

    //serialize
    public String toString() {
	String res="<"+name;
	for(int i=0;i<attributes.length;i++) {
	    res+=" "+attributes[i]+"=\""+values[i]+"\"";
	}
	res+=">";
	for(int i=0;i<children.length;i++)
	    res+=children[i].toString();
	res+="</"+name+">";
	return res;
    }

    public boolean isEmpty() {
	return children.length==0;
    }
}
